﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.ComponentModel.Composition;
using Kooboo.IoC;
using Kooboo.Domain;

namespace Kooboo.Commerce.Repositories
{
    [Export(typeof(IEntityDeleteCommand<IProductType>))]
    public class ProductTypeDeleteCommand:EntityDeleteCommand<IProductType>
    {
        protected override string TableName
        {
            get {
                return "ProductType";
            }
        }

        protected override string BuildCondition()
        {
            var ids = this.EntitySet.Select(i => i.Id).ToArray();
            var where = string.Empty;
            if (ids.Length == 0)
            {
                where = " 1=2 ";
            }
            else
            {
                where = " Id in (" + string.Join(", ", ids) + ") ";
            }

            return where;
        }

        public override void Execute()
        {
            var where = this.BuildCondition();

            var commandText = " DELETE FROM CustomField WHERE " + where.Replace("Id", "ProductTypeId");

            var context = ContextContainer.Current.Resolve<DataWriterContext>();

            context.ExecuteCommand(commandText);

            commandText = " DELETE FROM Variation WHERE " + where.Replace("Id", "ProductTypeId");

            context.ExecuteCommand(commandText);

            commandText = " DELETE FROM " + this.TableName + " WHERE " + where;

            context.ExecuteCommand(commandText);
        }
    }
}
